package com.pg_chat.utils;

import com.kennycason.kumo.CollisionMode;
import com.kennycason.kumo.WordFrequency;
import com.kennycason.kumo.bg.CircleBackground;
import com.kennycason.kumo.font.KumoFont;
import com.kennycason.kumo.font.scale.SqrtFontScalar;
import com.kennycason.kumo.nlp.FrequencyAnalyzer;
import com.kennycason.kumo.nlp.tokenizer.WordTokenizer;
import com.kennycason.kumo.nlp.tokenizers.ChineseWordTokenizer;
import com.kennycason.kumo.palette.LinearGradientColorPalette;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
public class WordCloud {

    private FrequencyAnalyzer frequencyAnalyzer = new FrequencyAnalyzer();
    private List<WordFrequency> wordFrequencies = new ArrayList<>();

    //词汇参数
    @Value("${wordCloud.frequencies:600}")
    private Integer WORD_FREQUENCIES;
    @Value("${wordCloud.minWordLength}")
    private Integer MIN_WORD_LENGTH;
    @Value("${wordCloud.tokenizer:chineseWordTokenizer}")
    private String WORD_TOKENIZER;

    //图像参数
    @Value("${wordCloud.dimension.width:500}")
    private Integer DIMENSION_WIDTH;
    @Value("${wordCloud.dimension.height:500}")
    private Integer DIMENSION_HEIGHT;
    @Value("${wordCloud.padding:2}")
    private Integer PADDING;//边框
    @Value("${wordCloud.circleRadius:255}")
    private Integer CIRCLE_RADIUS;
    @Value("${wordCloud.backgroundColor.red:255}")
    private Integer BACKGROUND_COLOR_RED;
    @Value("${wordCloud.backgroundColor.green:255}")
    private Integer BACKGROUND_COLOR_GREEN;
    @Value("${wordCloud.backgroundColor.blue:255}")
    private Integer BACKGROUND_COLOR_BLUE;

    //字体
    @Value("${wordCloud.font.name:STong-Light}")
    private String FONT_NAME;
    @Value("${wordCloud.font.style:2}")
    private Integer FONT_STYLE;
    @Value("${wordCloud.font.size:18}")
    private Integer FONT_SIZE;
    @Value("${wordCloud.sqrtFontScalar.min:12}")
    private Integer FONT_SCALAR_MIN;
    @Value("${wordCloud.sqrtFontScalar.max:42}")
    private Integer FONT_SCALAR_MAX;


    //初始化
    @PostConstruct
    public void init()  {
        frequencyAnalyzer.setWordFrequenciesToReturn(WORD_FREQUENCIES);
        frequencyAnalyzer.setMinWordLength(MIN_WORD_LENGTH);
    }

    /**
     * 设置词云样式
     * @return 词云类实例
     */
    private com.kennycason.kumo.WordCloud config4Cloud(){
        //加入分词并随机生成权重，每次生成得图片都不一样
        //test.stream().forEach(e-> wordFrequencies.add(new WordFrequency(e,new Random().nextInt(test.size()))));
        //此处不设置会出现中文乱码
        java.awt.Font font = new java.awt.Font(FONT_NAME, FONT_STYLE, FONT_SIZE);
        //设置图片分辨率
        Dimension dimension = new Dimension(DIMENSION_WIDTH, DIMENSION_HEIGHT);
        //此处的设置采用内置常量即可，生成词云对象
        com.kennycason.kumo.WordCloud wordCloud = new com.kennycason.kumo.WordCloud(dimension, CollisionMode.PIXEL_PERFECT);
        //设置边界及字体
        wordCloud.setPadding(PADDING);
        //因为我这边是生成一个圆形,这边设置圆的半径
        wordCloud.setBackground(new CircleBackground(CIRCLE_RADIUS));
        wordCloud.setFontScalar(new SqrtFontScalar(FONT_SCALAR_MIN, FONT_SCALAR_MAX));
        //设置词云显示的三种颜色，越靠前设置表示词频越高的词语的颜色
        wordCloud.setColorPalette(new LinearGradientColorPalette(Color.RED, Color.BLUE, Color.GREEN, 30, 30));
        wordCloud.setKumoFont(new KumoFont(font));
        wordCloud.setBackgroundColor(new Color(BACKGROUND_COLOR_RED, BACKGROUND_COLOR_GREEN, BACKGROUND_COLOR_BLUE));
        wordCloud.build(wordFrequencies);

        return wordCloud;
    }

    public void createWordCloud(String contentPath, String dest){

        wordTokenizerLanguageConfig();
        // 可以直接从文件中读取
        try {
            wordFrequencies = frequencyAnalyzer.load(contentPath);
        } catch (IOException e) {
            System.out.println("error");
            e.printStackTrace();
        }

        com.kennycason.kumo.WordCloud wordCloud = config4Cloud();
        //生成词云图路径
        wordCloud.writeToFile(dest);

    }

    public BufferedImage createWordCloud(List<String> texts){

        wordTokenizerLanguageConfig();
        wordFrequencies = frequencyAnalyzer.load(texts);

        com.kennycason.kumo.WordCloud wordCloud = config4Cloud();
        return wordCloud.getBufferedImage();

    }

    /**
     * 设置词云语言
     * @param tokenizer
     */
    public void changeLanguage4WordTokenizer(WordTokenizer tokenizer){
        this.frequencyAnalyzer.setWordTokenizer(tokenizer);
    }

    private void wordTokenizerLanguageConfig(){

        ApplicationContext app = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        WordTokenizer wordTokenizer = (WordTokenizer) app.getBean(WORD_TOKENIZER);
        frequencyAnalyzer.setWordTokenizer(wordTokenizer);
    }


    public static void main(String[] args) {
        WordCloud wordCloud = new WordCloud();
        if(args.length != 0)
            wordCloud.createWordCloud(args[0],args[1]);
        else
            wordCloud.createWordCloud("E:\\test.txt","E:\\wordCloud.png");
    }

}
